<?php
namespace App\Wen\Utils;

use App\Jobs\GatewayJob;
use App\Lib\GeTui\request\push\android\GTAndroid;
use App\Lib\GeTui\request\push\android\GTUps;
use App\Lib\GeTui\request\push\GTNotification;
use App\Lib\GeTui\request\push\GTPushBatchRequest;
use App\Lib\GeTui\request\push\GTPushChannel;
use App\Lib\GeTui\request\push\GTPushMessage;
use App\Lib\GeTui\request\push\GTPushRequest;
use App\Lib\GeTui\request\push\ios\GTAlert;
use App\Lib\GeTui\request\push\ios\GTAps;
use App\Lib\GeTui\request\push\ios\GTIos;
use App\Lib\JwtAuth;
use App\Lib\GeTui\GTClient;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Cache;

class GatewayUtils{

    /**
     * @param $title
     * @param $content
     * @param $payload
     * @param string $cid
     * @param string $way single|all|batch
     * @return array
     */
    public static function app_push($title, $content, $payload, $cids = '', $way = 'single'){
        if(is_array($payload)){
            $payload = json_encode($payload);
        }

        if($way != 'all' && _empty_($cids)){
            return [
                'code' => 200003,
                'raw' => '无cid',
                'msg' => '无cid'
            ];;
        }

        $content = _mini_phone(_mini_aite_replace(_mini_emoji($content, true), true), true);
        $content = preg_replace_callback('$<a [^>]*?>(.*?)</a>$', function ($r){
            return $r[1];
        }, $content);
        $content = strip_tags($content);

        $transmission_content = json_encode([
            'title' => $title,
            'content' => $content,
            'payload' => $payload
        ]);
        //创建API，APPID等配置参考 环境要求 进行获取
        $api = new GTClient("https://restapi.getui.com",Settings::get('uni_push_1_appkey'), Settings::get('uni_push_1_appid'),Settings::get('uni_push_1_master_secret'));
        if($way == 'all' || $way == 'single'){
            $push = self::get_push_object($title, $content, $payload, $transmission_content);
            //处理返回结果
            if($way == 'single'){
                $push->setCid(is_array($cids) ? _array_key($cids, 0, $cids) : $cids);
                $result = $api->pushApi()->pushToSingleByCid($push);
            }else if($way == 'all'){
                $result = $api->pushApi()->pushAll($push);
            }
        }else if($way == 'batch'){
            $batch = new GTPushBatchRequest();
            $msg_list = [];
            foreach ($cids as $cid){
                $push = self::get_push_object($title, $content, $payload, $transmission_content);
                $push->setCid($cid);
                $msg_list[] = $push;
            }
            $batch->setMsgList($msg_list);
            $batch->setIsAsync(false);
            $result = $api->pushApi()->pushBatchByCid($batch);
        }

        if($result && $result['code'] === 0){
            return [
                'code' => 0,
                'data' => $result['data']
            ];
        }else{
            return [
                'code' => $result['code'],
                'raw' => json_encode($result),
                'msg' => $result['code'].':'.$result['msg']
            ];
        }
    }

    private static function get_push_object($title, $content, $payload, $transmission_content){
        //设置推送参数
        $push = new GTPushRequest();
        $push->setRequestId('push_request_id_'.time().'');

        // 设置消息
        $message = new GTPushMessage();
        $notify = new GTNotification();
        $notify->setTitle($title);
        $notify->setBody($content);
        //点击通知后续动作，目前支持以下后续动作:
        //1、intent：打开应用内特定页面url：打开网页地址。2、payload：自定义消息内容启动应用。3、payload_custom：自定义消息内容不启动应用。4、startapp：打开应用首页。5、none：纯通知，无后续动作
        $notify->setClickType("payload");
        $notify->setPayload($payload);
        $notify->setBadgeAddNum(1);
//        $message->setNotification($notify);
        $message->setTransmission($transmission_content);
        $push->setPushMessage($message);


        // 设置push-channel
        $pushChannel = new GTPushChannel();
        $ios = new GTIos();
        $ios->setPayload($payload);
        $ios->setAutoBadge('+1');
        $ios->setType('notify');
        $aps = new GTAps();
        $alert = new GTAlert();
        $alert->setTitle($title);
        $alert->setBody($content);
        $aps->setAlert($alert);
        $ios->setAps($aps);

        $android = new GTAndroid();
        $ups = new GTUps();
        $ups->setTransmission($transmission_content);
        $android->setUps($ups);

        $pushChannel->setIos($ios);
        $pushChannel->setAndroid($android);
        $push->setPushChannel($pushChannel);
        return $push;
    }

    public static function pre_client_message($message){

        $message_arr = json_decode($message, true);
        if(_empty_($message_arr) || _empty_($message_arr['mode'])){
            return [];
        }

        if(!in_array($message_arr['mode'], ['bind', 'ping'])){
            return [];
        }

        if(_array_key($message_arr, 'token', '')){
            $token = $message_arr['token'];
            $played = $message_arr['played'] ?? 0;
            $player = 0;
            if($token && JwtAuth::verifyToken($token)){
                if($played > 0){
                    $uid = JwtAuth::getUserId($token,'uid');
                    // 管理员且在自己的马甲列表里
                    if(UserUtils::is_mini_supder_admin($uid)){
                        $player = $uid;
                        $uid = $played;
                    }
                }else{
                    $uid = JwtAuth::getUserId($token,'uid');
                }
                if($player > 0){
                    $message_arr['uid'] = $uid;
                    $message_arr['player'] = $player;
                }else{
                    $message_arr['uid'] = $uid;
                }
            }
        }

        return $message_arr;

    }

    public static function responceModes(){
        return [
            0 => 'bind_success',
            1 => 'on_connected',
            2 => 'heart',
            3 => 'client_disconnected',
            4 => 'test',
            5 => 'chat_message',
            6 => 'has_refresh',
            7 => 'video_snapshot_finish',
            8 => 'warn_system_message',
            9 => 'success_system_message',
            10 => 'info_system_message',
            11 => 'error_system_message',
            12 => 'update_userinfo',
            13 => 'refresh_global_config',
            14 => 'task_reward',
            15 => 'app_badge',
            16 => 'create_push_message',
            17 => 'pull_down_refresh',
            18 => 'get_system_info',
            19 => 'order_confirm',
            999 => 'toUrl'
        ];
    }

    public static function send($client_id, $msg){
        if(_empty_($client_id)){
            return;
        }

        if($client_id == 'all'){
            Gateway::sendToAll($msg);
        }else{
            Gateway::sendToClient($client_id, $msg);
        }
    }

    public static function warn_message($client_id, $content){
        return self::success($client_id, 8, ['content'=>$content]);
    }

    public static function info_message($client_id, $content){
        return self::success($client_id, 10, ['content'=>$content]);
    }

    public static function success_message($client_id, $content){
        return self::success($client_id, 9, ['content'=>$content]);
    }

    public static function error_message($client_id, $content){
        return self::success($client_id, 11, ['content'=>$content]);
    }

    public static function message_arr($mode, $data = [],$code =200){
        return [
            'status'  => true,
            'code'    => $code,
            'mode'    => $mode,
            'tip'     => self::responceModes()[$mode],
            'message' => config('errorcode.code')[(int)$code],
            'data'    => $data,
        ];
    }

    public static function success($client_id, $mode, $data = [],$code =200)
    {
        if(_empty_($client_id)){
            return false;
        }
        global $__MINI_GLOBAL_PAYCODE_6__;
        if(!$__MINI_GLOBAL_PAYCODE_6__){
            if(!in_array($mode, [0, 1, 2, 3, 4, 12, 13])){
                return false;
            }
        }
        if($mode == 13){
            if(_empty_(_array_key($data, 'file', ''))){
                return false;
            }
        }
        GatewayJob::dispatch($client_id, json_encode([
            'status'  => true,
            'code'    => $code,
            'mode'    => $mode,
            'tip'     => self::responceModes()[$mode],
            'message' => config('errorcode.code')[(int)$code],
            'data'    => $data,
        ]));
        return true;
    }

    public static function fail($client_id, $code, $data = [])
    {
        if(_empty_($client_id)){
            return false;
        }
        GatewayJob::dispatch($client_id, json_encode([
            'status'  => false,
            'code'    => $code,
            'message' => config('errorcode.code')[(int) $code],
            'data'    => $data,
        ]));
        return true;
    }


    public static function uid2client_id($uid){
        if(_empty_($uid)){
            return null;
        }
        return Cache::get('websocket:uid2clientid:'.$uid);
    }

    public static function client_id2uid($client_id){
        if(_empty_($client_id)){
            return null;
        }
        return Cache::get('websocket:clientid2uid:'.$client_id);
    }

}
